import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import useAuthStore from '@/store/auth'
import pinia from '@/store'
import { LOGIN_URL } from '@/config'

const router = createRouter({
  history: createWebHistory(),

  routes: routes,

  // 滚动行为（切换路由时将滚动条置于初始位置）
  scrollBehavior() {
    return { left: 0, top: 0 }
  },
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore(pinia)

  document.title = to.meta.title || ''

  // 已登录
  if (authStore.isLogin()) {
    // 加载用户信息
    if (!authStore.username) {
      try {
        await authStore.getUserInfo()
      } catch (_) {
        authStore.clear()
        return next({ path: LOGIN_URL, query: { redirect: to.path } })
      }
    }
    // 未登录
  } else {
    if (to.meta.auth) {
      return next({
        path: LOGIN_URL,
        query: { redirect: to.path == '/' ? undefined : to.path },
      })
    }
  }

  return next()
})

export default router
